package cc.customer.system.service.impl;

import cc.customer.cRound.dao.CRoundConfigMapper;
import cc.customer.cRound.dao.CRoundLevelMapper;
import cc.customer.cRound.domain.CRoundConfig;
import cc.customer.cRound.domain.CRoundLevel;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.domain.Tree;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.TreeUtils;
import cc.customer.system.dao.CDingUserMapper;
import cc.customer.system.dao.DeptMapper;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.CDingConfig;
import cc.customer.system.domain.CDingUser;
import cc.customer.system.domain.Dept;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.DeptService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("deptService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeptServiceImpl extends BaseService<Dept> implements DeptService {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private CRoundConfigMapper configMapper;

	@Autowired
	private CDingUserMapper cDingUserMapper;

	@Autowired
	private CRoundLevelMapper levelMapper;

	@Override
	public Tree<Dept> getDeptTree() {
		List<Tree<Dept>> trees = new ArrayList<>();
		List<Dept> depts = this.findAllDepts(new Dept());
		depts.forEach(dept -> {
			Tree<Dept> tree = new Tree<>();
			tree.setId(dept.getDeptId().toString());
			tree.setParentId(dept.getParentId().toString());
			tree.setText(dept.getDeptName());
			trees.add(tree);
		});
		return TreeUtils.build(trees);
	}

	@Override
	public List<Dept> findAllDepts(Dept dept) {
		try {
			Example example = new Example(Dept.class);
			if (StringUtils.isNotBlank(dept.getDeptName())) {
				example.createCriteria().andCondition("dept_name=", dept.getDeptName());
			}
			example.setOrderByClause("dept_id");
			return this.selectByExample(example);
		} catch (Exception e) {
			log.error("获取部门列表失败", e);
			return new ArrayList<>();
		}

	}

	@Override
	public Dept findByName(String deptName) {
		Example example = new Example(Dept.class);
		example.createCriteria().andCondition("lower(dept_name) =", deptName.toLowerCase());
		List<Dept> list = this.selectByExample(example);
		return list.isEmpty() ? null : list.get(0);
	}

	@Override
	@Transactional
	public void addDept(Dept dept) {
		Long parentId = dept.getParentId();
		if (parentId == null)
			dept.setParentId(0L);
		dept.setCreateTime(new Date());
		this.save(dept);
	}

	@Override
	@Transactional
	public void deleteDepts(String deptIds) {
		List<String> list = Arrays.asList(deptIds.split(","));
		this.batchDelete(list, "deptId", Dept.class);
		this.deptMapper.changeToTop(list);
	}

	@Override
	/**人员和部门树状结构 ----禁用部门**/
	public JSONArray getDeptAndUserTree() {
		JSONArray jsonarray = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", "0");
			List<Dept> list = this.selectByExample(example);
			Map<String,Boolean> map = new HashMap<>();
			map.put("disabled",true);
			list.forEach( lis ->{
				JSONObject json = new JSONObject();
				json.put("id","jpet"+lis.getDeptId());
				json.put("text",lis.getDeptName());
				json.put("children",getChile(lis.getDeptId()+""));
				json.put("state",map);
				json.put("icon",null);
				jsonarray.add(json);
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsonarray;
	}

	//大搜根据项目获取配置的部门和人员
	@Override
	public ResponseBo selectDingByCRound(String puuid,String type,String deptid){
		try {
			CRoundLevel level = new CRoundLevel();
			level.setlUuid(puuid);
			level.setlType(type);
			level.setlDeptid(deptid);
			List<CRoundLevel> listDept = levelMapper.selectByPidAndDept(level);

			List<String> list = new ArrayList<>();
			if (listDept.size() >0 ){
				for(CRoundLevel roundLevel:listDept){
					String  users = roundLevel.getlIntPerson();
					if (!StringUtils.isEmpty(users)){
						list.addAll(Arrays.asList(users.split(",")));
					}
				}
			}
			List<CDingUser> listUsers =cDingUserMapper.selectDingUserByDept(deptid);
			JSONArray array = new JSONArray();

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("selected",true);

			listUsers.forEach( lis ->{
				JSONObject json = new JSONObject();
				json.put("id",lis.getcDUsername());
				String grade = "";
				if(!StringUtils.isEmpty(lis.getcDGrade())){
					grade = lis.getcDGrade();
				}
				json.put("text",lis.getcDName()+"&emsp;&emsp;&emsp;&emsp;"+grade);
				if (list.contains(lis.getcDUsername())){ json.put("state",jsonObject); }
				json.put("icon",null);
				array.add(json);
			});
			return ResponseBo.ok("",array);
		}catch (Exception e){
			e.printStackTrace();
		}
		return ResponseBo.error();
	}

	@Override
	/**人员和部门树状结构 ----启用部门**/
	public JSONArray getDeptAndUserTreeByDept() {
		JSONArray jsonarray = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", "0");
			List<Dept> list = this.selectByExample(example);
			list.forEach( lis ->{
				JSONObject json = new JSONObject();
				json.put("id","jpet"+lis.getDeptId());
				json.put("text",lis.getDeptName());
				json.put("children",getChile(lis.getDeptId()+""));
				json.put("icon",null);
				jsonarray.add(json);
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsonarray;
	}

	@Override
	public JSONArray getDeptAndUserTreeByRoles(Long deptid) {
		JSONArray jsonarray = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("DEPT_ID =", deptid);
			List<Dept> list = this.selectByExample(example);
			list.forEach( lis ->{
				JSONObject json = new JSONObject();
				json.put("id","jpet"+lis.getDeptId());
				json.put("text",lis.getDeptName());
				json.put("children",getChile(lis.getDeptId()+""));
				json.put("icon",null);
				jsonarray.add(json);
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsonarray;
	}

	@Override
	public JSONArray getDeptToJSTree() {
		JSONArray jsonarray = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", "0");
			List<Dept> list = this.selectByExample(example);
			list.forEach( lis ->{
				JSONObject json = new JSONObject();
				json.put("id",lis.getDeptId());
				json.put("text",lis.getDeptName());
				json.put("children",getChiledept(lis.getDeptId()+""));
				json.put("icon",null);
				jsonarray.add(json);
			});
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsonarray;
	}
	/**递归查询部门**/
	private JSONArray getChiledept(String id){
		JSONArray jsion = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", id);
			List<Dept> list = this.selectByExample(example);
			if (!list.isEmpty()){
				list.forEach( lis ->{
					JSONObject json = new JSONObject();
					json.put("id",lis.getDeptId());
					json.put("text",lis.getDeptName());
					json.put("children",getChile(lis.getDeptId()+""));
					json.put("icon",null);
					jsion.add(json);
				});
			}else{
				return jsion;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsion;
	}
	/***递归和循环查询 部门和user**/
	private JSONArray getChile(String id){
		JSONArray jsion = new JSONArray();
		try {
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", id);
			/****查询当前部门下的人数***/
			Example example1 = new Example(MyUser.class);
			example1.createCriteria().andCondition("DEPT_ID = ",id);

			List<MyUser> listAllUser = userMapper.findUserByDepid(id);
			if (!listAllUser.isEmpty()){
				listAllUser.forEach(listallinfo ->{
					JSONObject json = new JSONObject();
					json.put("id",listallinfo.getUserUuid());
					json.put("text",listallinfo.getNickname());
					json.put("children","");
					json.put("icon",null);
					jsion.add(json);
				});
			}
			List<Dept> list = this.selectByExample(example);
			if (!list.isEmpty()){
				Map<String,Boolean> map = new HashMap<>();
				map.put("disabled",true);
				list.forEach( lis ->{
					JSONObject json = new JSONObject();
					json.put("id","jpet"+lis.getDeptId());
					json.put("text",lis.getDeptName());
					json.put("children",getChile(lis.getDeptId()+""));
					json.put("icon",null);
					json.put("state",map);
					jsion.add(json);
				});
			}else{
				return jsion;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsion;
	}


	/***递归和循环查询 部门和user**/
	private JSONArray getCRoundChile(String id){
		JSONArray jsion = new JSONArray();
		try {

			List<CDingUser> listAllUser =cDingUserMapper.selectDingUserByDept(id);
			if (!listAllUser.isEmpty()){
				listAllUser.forEach(listallinfo ->{
					JSONObject json = new JSONObject();
					json.put("id",listallinfo.getcDUsername());
					String grade = "";
					if(!StringUtils.isEmpty(listallinfo.getcDGrade())){
						grade = listallinfo.getcDGrade();
					}
					json.put("text",listallinfo.getcDName()+"&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;"+grade);
					json.put("children","");
					json.put("icon",null);
					jsion.add(json);
				});
			}
			Example example = new Example(Dept.class);
			example.createCriteria().andCondition("PARENT_ID =", id);
			List<Dept> list = this.selectByExample(example);
			if (!list.isEmpty()){
				Map<String,Boolean> map = new HashMap<>();
				map.put("disabled",true);
				list.forEach( lis ->{
					JSONObject json = new JSONObject();
					json.put("id","jpet"+lis.getDeptId());
					json.put("text",lis.getDeptName());
					json.put("children",getCRoundChile(lis.getDeptId()+""));
					json.put("icon",null);
					json.put("state",map);
					jsion.add(json);
				});
			}else{
				return jsion;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return jsion;
	}


	@Override
	public Dept findById(Long deptId) {
		return this.selectByKey(deptId);
	}

	@Override
	@Transactional
	public void updateDept(Dept dept) {
		this.updateNotNull(dept);
	}


}
